<?php

namespace Page;

use Base\Contents;
use W3\Util;

/**
 * 内容组件
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Rows extends Contents
{
    /**
     * 初始化
     *
     * @access protected
     * @return void
     */
    protected function init()
    {
		# 定义变量默认数据
        $this->parameter([
			
		    'field' => '*',	
			'alias' => '',
			'uid' => 0,
			'cid' => 0,
		    'sort' => 'cid',
            'desc' => true,
			'offset' => 0,
			'limit' => 0	
			
		], true);
	}
	
    /**
     * 执行函数,初始化数据
     *
     * @access public
     * @return void
     */
    public function execute()
    {

		$pass = false;
		$select = $this->select($this->parameter->field)
		    ->where('table.contents.type = ?', 'page')
			->where('table.contents.status = ?', 'publish');

		if($this->parameter->uid){
			$select->where('table.contents.uid = ?', $this->parameter->uid);
			$pass = true;
		}

		if($this->parameter->alias){ 
		    $select->where('table.contents.alias = ?', $this->parameter->alias);
			$pass = true;
		}

		if($this->parameter->cid){
			if(FALSE !== strpos($this->parameter->cid, ',')){ 
	            $cidList = array_filter(explode(',', $this->parameter->cid), function($val){
	                return is_numeric($val);
	            });
				if($cidList){ 
				    $select->where('table.contents.cid IN ('.substr( str_repeat( '?,', count( $cidList ) ), 0, - 1 ).')', $cidList);
				    $pass = true;
				} else {
				    $pass = false;
			    }
			}else{
		        $select->where('table.contents.cid = ?', $this->parameter->cid);
				$pass = true;
			}
		}

        //去掉自定义首页
        if ($frontPage = $this->config->frontPage) {
            $select->where('table.contents.cid <> ?', $frontPage);
        }

        if ($this->parameter->limit > 0) {
            $select->limit($this->parameter->limit);
			$pass = true;
        }

        if ($this->parameter->offset > 0) {
            $select->offset($this->parameter->offset);
        }
		
        if($pass){
			if(isset($cidList)){
			    $list = Util::arrayChangeKey($select->get(), 'mid');
                foreach ($cidList as $v) {
                    isset($list[$v]) && $this->push($list[$v]);
                }
			} else {
			    if($this->parameter->sort){
				    $select->order('table.contents.' . $this->parameter->sort, $this->parameter->desc ? 'DESC' : 'ASC');
			    } 
				$select->get([$this, 'push']);
			}
        }
    }
}
